package me.evis.mobile.sms2cal;

import java.util.Date;

import me.evis.mobile.sms2cal.provider.ParsedEventContentProvider;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.ToggleButton;

public class Main extends Activity {
    /** Tag string for our debug logs */
    private static final String TAG = "me.evis.mobile.sms2cal.Main";
    
    private final int MENU_ITEM_PREFERENCE = Menu.FIRST;  
    private final int MENU_ITEM_CALENDAR = Menu.FIRST + 1;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        if (getIntent().getData() == null) {
            getIntent().setData(ParsedEventContentProvider.CONTENT_URI);
        }
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        
        boolean parserEnabled = initParserByPreference();
        initAppSwitchBtn(parserEnabled);
        initEventList();
    }
    
    /** 
     * Add menu items
     * 
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     */
    public boolean onCreateOptionsMenu(Menu menu) {  
        menu.add(0, MENU_ITEM_PREFERENCE, 0, R.string.menu_item_preference)
            .setIcon(R.drawable.ic_menu_preferences);  
        menu.add(0, MENU_ITEM_CALENDAR, 0, R.string.menu_item_calendar)
            .setIcon(R.drawable.ic_menu_my_calendar);  
        return true;  
    }
     
    /** 
     * Define menu action
     * 
     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
     */
    public boolean onOptionsItemSelected(MenuItem item) {  
        switch (item.getItemId()) {
            case MENU_ITEM_PREFERENCE:
                startActivity(new Intent(this, Preference.class));
                
                break;
            case MENU_ITEM_CALENDAR:
                // Bring up Google Android Calendar
                Intent calendarIntent = new Intent() ;
                calendarIntent.putExtra("beginTime", new Date().getTime());
                calendarIntent.setClassName("com.android.calendar","com.android.calendar.AgendaActivity");
                try {
                    startActivity(calendarIntent);
                } catch (ActivityNotFoundException e) {
                    Log.e(TAG, "Seems Android Calendar app not exist. ", e);
                    Toast.makeText(this, R.string.android_calendar_not_installed, Toast.LENGTH_SHORT).show();
                }
                
                break;
        }
        return false;  
    }
    
    private boolean initParserByPreference() {
        SharedPreferences preferences = 
                PreferenceManager.getDefaultSharedPreferences(this);
        boolean settingsParserEnabled = 
                preferences.getBoolean(getString(R.string.prefkey_parser_enabled), true);
        enableParser(settingsParserEnabled);
        return settingsParserEnabled;
    }
    
    private void initAppSwitchBtn(boolean enabled) {
        getAppSwitchBtn().setChecked(enabled);
        
        getAppSwitchBtn().setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferences preferences = 
                        PreferenceManager.getDefaultSharedPreferences(Main.this);
                preferences.edit().putBoolean(getString(R.string.prefkey_parser_enabled), isChecked).commit();
                enableParser(isChecked);
            }
        });
    }
    
    private void initEventList() {
        Cursor c = managedQuery(getIntent().getData(), null, null, null, null);
        ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.parsedevent_list_row, c, 
                new String[] {
                    ParsedEventContentProvider.PARSELOG_ID, 
                    ParsedEventContentProvider.SMS_FROM, 
                    ParsedEventContentProvider.DTSTART, 
                    ParsedEventContentProvider.SMS_BODY
                }, 
                new int[] {
                    R.id.parseLogId, 
                    R.id.parseLogSmsFrom, 
                    R.id.parseLogDate, 
                    R.id.parseLogSmsBody
                });
        getEventList().setAdapter(adapter);
        getEventList().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startActivity(new Intent(Intent.ACTION_VIEW, 
                        ContentUris.withAppendedId(getIntent().getData(), id)));
            }
        });
    }
    
    private void enableParser(boolean enable) {
        Log.d(TAG, (enable ? "Enabling" : "Disabling") + " SMS receiver");
        
        // Enable or disable the broadcast receiver depending on the checked
        // state of the toggle button.
        final PackageManager pm = this.getPackageManager();
        final ComponentName componentName = 
                new ComponentName("me.evis.mobile.sms2cal", "me.evis.mobile.sms2cal.SmsReceiver");
        final boolean enabled = pm.getComponentEnabledSetting(componentName) ==
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
        
        if (enable != enabled) {
            pm.setComponentEnabledSetting(componentName,
                    enable ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                            : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP);
            Log.d(TAG, (enable ? "Enabled" : "Disabled") + " SMS receiver");
        } else {
            Log.d(TAG, " SMS receiver already " + (enable ? "enabled" : "Disabled"));
        }
    }
    
    private ToggleButton getAppSwitchBtn() {
        return (ToggleButton) findViewById(R.id.appSwitchBtn);
    }
    
    private ListView getEventList() {
        return (ListView) findViewById(R.id.eventList);
    }
}